package com.example.user.controller;

import com.example.common.api.UserService;
import com.example.common.entity.ResultMessage;
import com.example.common.entity.Token;
import com.example.common.entity.User;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

/**
 * @author kangshuai
 */
@RestController
@RequestMapping("user")
public class UserController {

    @Resource
    private UserService userService;


    /**
     * 注册
     *
     * @param user
     * @return
     * @throws Exception
     */
    @PostMapping(value = "register", produces = {"application/json;charset=UTF-8"})
    public ResultMessage<Boolean> register(@RequestBody User user) throws Exception {
        ResultMessage<Boolean> resultMessage = userService.register(user.getEmail(), user.getPassword(), user.getCode());
        return resultMessage;
    }


    /**
     * 用户登录
     *
     * @param user
     * @param response
     * @return
     * @throws Exception
     */
    @PostMapping(value = "login", produces = {"application/json;charset=UTF-8"})
    public ResultMessage<Token> login(@RequestBody User user, HttpServletResponse response) throws Exception {
        Token token = userService.login(user.getEmail(), user.getPassword());

        if (token == null) {
            return ResultMessage.error("用户名或者密码错误", null);
        }

        // 创建一个 cookie对象
        Cookie cookie = new Cookie("spring_cloud_token", token.getToken());
        cookie.setPath("/");
        //将cookie对象加入response响应
        response.addCookie(cookie);

        return ResultMessage.success(token);
    }

    @PostMapping(value = "info", produces = {"application/json;charset=UTF-8"})
    public ResultMessage<String> info(@RequestBody Token token) throws Exception {
        String email = userService.getInfoByToken(token.getToken());
        return ResultMessage.success(email);
    }

}
